package com.aoyy.controller;

import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;
import com.aoyy.model.User;
import com.aoyy.model.Topic;
import com.aoyy.model.Board;
import com.aoyy.model.BoardManager;
import com.aoyy.service.UserService;
import com.aoyy.service.TopicService;
import com.aoyy.service.BoardService;
import com.aoyy.service.BoardManagerService;
import com.aoyy.util.Page;
import com.aoyy.constant.Constants;
/**===================================================================================
 * Topic controller <code>TopicController</code> 
 * @author this author
 * @date 2017-08-14
 * =================================================================================== */
@Controller
public class TopicController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private BoardService boardService;
    @Autowired
    private BoardManagerService boardManagerService;
	private Integer pageNo;
	
    // Display topic list
	@RequestMapping(value="/topic/topicList-{boardId}", method={RequestMethod.GET})
	public String toTopicsByBoardId(HttpServletRequest request, @RequestParam(value="pageNo", required=false) Integer pageNo, @PathVariable Integer boardId) {
		User user = (User) this.getSessionUser(request);
		BoardManager boardManager = null;
		if (user != null) {
			boardManager = boardManagerService.queryBoardManagerByBoardIdAndUserId(boardId, user.getUserId());
		}
		request.setAttribute("boardManager", boardManager);
	    pageNo = (pageNo == null) ? 1 : pageNo;
		this.pageNo = pageNo;
		Page pagedTopics = topicService.pagedQuery(pageNo, Constants.PAGE_SIZE, boardId);
		request.setAttribute("pagedTopics", pagedTopics);
		Board board = boardService.queryBoardByBoardId(boardId);
		request.setAttribute("board", board);
		this.setSessionTopicPathURl(request, "/topic/topicList-" + boardId);
		return "/topic/topicList";
	}
	
	// Update topic digest by boardId & userId
	@RequestMapping(value="/topic/topicList/{checkedTopicIdBoardId}", method={RequestMethod.GET}) 
	public String toTopicsByCheckedTopicIdBoardId(HttpServletRequest request, @RequestParam(value="pageNo", required=false) Integer pageNo, @PathVariable String checkedTopicIdBoardId) {
		String[] str = checkedTopicIdBoardId.split("-");
		Integer checked = Integer.valueOf(str[0]);
		Integer topicId = Integer.valueOf(str[1]);
		Integer boardId = Integer.valueOf(str[2]);
		topicService.updateTopicDigest(topicId, checked);
		User user = (User) this.getSessionUser(request);
		userService.updateUserCreditOfDigestTopic(user.getUserId(), checked);
        
		BoardManager boardManager = boardManagerService.queryBoardManagerByBoardIdAndUserId(boardId, user.getUserId());
		request.setAttribute("boardManager", boardManager);
		pageNo = (pageNo == null) ? this.pageNo : pageNo;
		Page pagedTopics = topicService.pagedQuery(pageNo, Constants.PAGE_SIZE, boardId);
		request.setAttribute("pagedTopics", pagedTopics);
		Board board = boardService.queryBoardByBoardId(boardId);
		request.setAttribute("board", board);
		this.setSessionTopicPathURl(request, "/topic/topicList-" + boardId);
		System.err.println(board.getBoardId());
		return "/topic/topicList";
	}
	
	// To add topic by boadId
	@RequestMapping(value="/topic/addTopic-{boardId}", method={RequestMethod.GET})
	public String toAddTopic(@PathVariable Integer boardId, Map<String, Object> map) {
		map.put("boardId", boardId);
		return "/topic/addTopic";
	}
	
	// Add topic 
	@RequestMapping(value="/topic/addTopic-{boardId}", method={RequestMethod.POST})
	public ModelAndView addTopic(HttpServletRequest request, @RequestParam(value="pageNo", required=false) Integer pageNo, @PathVariable Integer boardId, Topic topic) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/topic/addTopic");
		if (topic.getTitle() == null || topic.getTitle().isEmpty()){
			view.addObject("message", "Title is required.");
			return view;
		}
		if (topic.getTitle().length() > 255) {
			view.addObject("message", "Title is requried and no more than 255 characters.");
		    return view;
		}
		if (topic.getContent() == null || topic.getContent().isEmpty()) {
			view.addObject("message", "Content is required.");
			return view;
		}
		Board board = new Board();
		board.setBoardId(boardId);
		topic.setBoard(board);
		User user = (User) this.getSessionUser(request);
		topic.setUser(user);
		topic.setCreateTime(new Date());
		topic.setViews(0);
		topic.setDigest(Constants.DIGEST_NO);
		topicService.save(topic);
		userService.updateUserCreditByEmitOrRemoveTopic(user.getUserId(), Constants.TOPIC_EMIT);
		view.addObject("message", "Add Topic Success!");
		return view;
	}
	
	// To delete topic by boadId & topicId
    @RequestMapping(value="/topic/deleteTopic-{topicId}", method={RequestMethod.GET})
	public String toDeleteTopic(@PathVariable Integer topicId, Map<String, Object> map) {
		Topic topic = topicService.queryTopicByTopicId(topicId);
		map.put("topic", topic);
		map.put("message", "Do you confirm to delete this topic?");
		return "/topic/deleteTopic";
	}
	
    // Delete topic by boadId & topicId
    @RequestMapping(value="/topic/deleteTopic-{topicId}", method={RequestMethod.POST})
	public ModelAndView deleteTopic(HttpServletRequest request, @RequestParam(value="pageNo", required=false) Integer pageNo, @PathVariable Integer topicId) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/topic/deleteTopic");
		if (topicId == null) {
			view.addObject("message", "This topic has been deleted.");
			return view;
		}
    	Topic topic = topicService.queryTopicByTopicId(topicId);
		topicService.delete(topic);
		userService.updateUserCreditByEmitOrRemoveTopic(topic.getUser().getUserId(), Constants.TOPIC_REMOVE);
		request.setAttribute("message", "Delete Topic Success!");
    	return view;
	}
    
    // To update topic by topicId
    @RequestMapping(value="/topic/updateTopic-{topicId}", method={RequestMethod.GET})
	public String toUpdateTopic(@PathVariable Integer topicId, Map<String, Object> map) {
		Topic topic = topicService.queryTopicByTopicId(topicId);
		map.put("topic", topic);
		return "/topic/updateTopic";
	}
    
    // Update topic by topicId
    @RequestMapping(value="/topic/updateTopic-{topicId}", method={RequestMethod.POST})
    public ModelAndView updateTopic(@RequestParam(value="pageNo", required=false) Integer pageNo, @PathVariable Integer topicId, Topic topic) {
    	ModelAndView view = new ModelAndView();
    	view.setViewName("/topic/updateTopic");
    	if (topic.getTitle() == null || topic.getTitle().isEmpty()) {
    		view.addObject("message", "Title is required");
    		return view;
    	}
    	if (topic.getTitle().length() > 255) {
    		view.addObject("message", "Title is required and no more than 255 characters.");
    		return view;
    	}
    	if (topic.getContent() == null || topic.getContent().isEmpty()) {
    		view.addObject("message", "Content is required.");
    		return view;
    	}
    	Topic topic2 = topicService.queryTopicByTopicId(topicId);
    	topic2.setTitle(topic.getTitle());
    	topic2.setContent(topic.getContent());
    	topicService.update(topic2);
    	view.addObject("message", "Update Topic Success!");
    	return view;
    }

}
